package com.devenv.repository;

import com.devenv.entity.SoftwareVersion;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

/**
 * 软件版本Repository
 */
@Repository
public interface SoftwareVersionRepository extends JpaRepository<SoftwareVersion, Long> {

    /**
     * 根据软件ID查找所有版本，按发布日期倒序排列
     */
    List<SoftwareVersion> findBySoftwareIdOrderByReleaseDateDesc(Long softwareId);

    /**
     * 根据软件ID查找最新版本
     */
    Optional<SoftwareVersion> findBySoftwareIdAndIsLatestTrue(Long softwareId);

    /**
     * 根据软件ID和版本号查找
     */
    Optional<SoftwareVersion> findBySoftwareIdAndVersion(Long softwareId, String version);

    /**
     * 查找所有最新版本
     */
    @Query("SELECT sv FROM SoftwareVersion sv WHERE sv.isLatest = true")
    List<SoftwareVersion> findAllLatestVersions();

    /**
     * 根据软件名称查找最新版本
     */
    @Query("SELECT sv FROM SoftwareVersion sv JOIN sv.software s WHERE s.name = :softwareName AND sv.isLatest = true")
    Optional<SoftwareVersion> findLatestVersionBySoftwareName(@Param("softwareName") String softwareName);

    /**
     * 根据软件ID和状态查找版本，按发布日期倒序
     */
    List<SoftwareVersion> findBySoftwareIdAndStatusOrderByReleaseDateDesc(Long softwareId, String status);

    /**
     * 根据状态查找版本，按发布日期倒序分页
     */
    Page<SoftwareVersion> findByStatusOrderByReleaseDateDesc(String status, Pageable pageable);

    /**
     * 根据软件ID和状态查找版本，排除指定ID，按发布日期倒序
     */
    List<SoftwareVersion> findBySoftwareIdAndStatusAndIdNotOrderByReleaseDateDesc(Long softwareId, String status, Long excludeId);

    /**
     * 清除指定软件的最新版本标记
     */
    @Modifying
    @Query("UPDATE SoftwareVersion sv SET sv.isLatest = false WHERE sv.softwareId = :softwareId")
    void clearLatestVersionBySoftwareId(@Param("softwareId") Long softwareId);
}
